//
//  LHUserAccountModel.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/12.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

class LHUserAccountModel: NSObject {
    static let sharedUserAccount: LHUserAccountModel = LHUserAccountModel()
    
    var userAccount: LHUserAccount?
    
    override init() {
        super.init()
        userAccount = LHUserAccount.loadUserAccount()
        
        //暂且在这调用一下获取首页数据的接口
//        LHNetWorkTools.sharedTools.requestStatus((userAccount?.access_token)!) { (response, error) -> () in
//            print(response)
//        }
    }
    
    
    var isLogin: Bool {
        return accessToken != nil
    }
    
    var accessToken: String? {
        guard let token = userAccount?.access_token else{
            return nil
        }
        
        let result = userAccount?.exeiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            //没有过期
            return token
        }else{
            return nil
        }
    }
    
    
    
    //  获取accesstoken
    func requestAccessToken(code: String, complete: (isSuccess: Bool)->()) {
        LHNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else {
                print("数据不是一个正确的json格式")
                complete(isSuccess: false)
                return
            }
            
            let userAccount = LHUserAccount(dict: dict)
            self.requestUserInfo(userAccount, complete: complete)
            
        }
    }
    
    
    //  获取用户信息
    func requestUserInfo(userAccount: LHUserAccount, complete: (isSuccess: Bool)->()) {
        
       LHNetWorkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
        
        if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
        }
        
        guard let dict = response as? [String: AnyObject] else {
            print("数据不是一个正确的json格式")
            complete(isSuccess: false)
            return
        }
        
        //到这一步dict已经获取了正确的数据
        userAccount.name = dict["name"] as? String
        userAccount.avatar_large = dict["avatar_large"] as? String
        self.userAccount = userAccount

        //归档数据
        let result = userAccount.saveUserAccount()

        if result {
            complete(isSuccess: true)
        }else{
            complete(isSuccess: false)
        }
        
        }
    }
}
